package com.bawei.bydayzg_two.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.bean.CartItem0
import com.bawei.base.mvvm.BaseFragment
import com.bawei.base.param.OrderDetail
import com.bawei.base.param.PPreOrder
import com.bawei.bydayzg_two.R
import com.bawei.bydayzg_two.adapter.CartAdapter
import com.bawei.bydayzg_two.databinding.FragmentCartBinding
import com.bawei.bydayzg_two.viewModel.CartViewModel
import com.blankj.utilcode.util.ToastUtils

class CartFragment : BaseFragment<FragmentCartBinding,CartViewModel>() {
    lateinit var cartAdapter: CartAdapter
    //
    override fun getLoutyId(): Int {
        return R.layout.fragment_cart
    }

    override fun getViewModel(): Class<CartViewModel> {
        return CartViewModel::class.java
    }

    override fun initView() {

        //
        cartAdapter = CartAdapter()
        binding.rvCart.adapter = cartAdapter
        binding.rvCart.layoutManager = LinearLayoutManager(requireActivity())
        //
        viewModel.cart("true","10","1")

        //点击item的3个控件，都可以控制金额变化
        cartAdapter.addChildClickViewIds(R.id.cart_add,R.id.cart_sub,R.id.cart_cb)
        //
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.cart_add -> {
                    //
                    cartAdapter.data[position].cartNum++
                    (cartAdapter.getViewByPosition(position,R.id.cart_num) as TextView).text = cartAdapter.data[position].cartNum.toString()
                    ( cartAdapter.getViewByPosition(position,R.id.cart_sub) as TextView).isEnabled = true
                    //接口调用
                    viewModel.cartUpdate(cartAdapter.data[position].id,cartAdapter.data[position].cartNum)
                }
                //
                R.id.cart_sub -> {
                    cartAdapter.data[position].cartNum--
                    (cartAdapter.getViewByPosition(position,R.id.cart_num) as TextView).text = cartAdapter.data[position].cartNum.toString()
                    //
                    if (cartAdapter.data[position].cartNum == 1){
                       ( cartAdapter.getViewByPosition(position,R.id.cart_sub) as TextView).isEnabled = false
                    }
                    viewModel.cartUpdate(cartAdapter.data[position].id,cartAdapter.data[position].cartNum)
                    //
                }
                //
                R.id.cart_cb -> {
                    //页面上选中状态发生了变化 适配器。数据发生了变化接口 没有变
                    cartAdapter.data[position].isChecked = !cartAdapter.data[position].isChecked
                }
            }
            //计算底部金额，和选中状态
            checkAmount()
        }
        //全选
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            //点击cb  rv的选中状态全部发生变化
            binding.cb.setOnClickListener {
                cartAdapter.data.forEach {
                    it.isChecked = isChecked
                }
            }
            //
            cartAdapter.notifyDataSetChanged()
            checkAmount()
        }

        //点击管理  文字变成 “取消” 同事金额和下单消失，再次点击回复原来的
        binding.tvManage.setOnClickListener {
            if (binding.tvManage.text.toString() == "管理"){
                binding.tvManage.text = "取消"
                binding.llManage.isVisible = false
                binding.llCancel.isVisible = true
            } else {
                binding.tvManage.text = "管理"
                binding.llManage.isVisible = true
                binding.llCancel.isVisible = false
            }
        }

        //点击管理判断是否有选中的商品，有的话进行删除
        binding.tvDelte.setOnClickListener {
            var count = 0//显示选中的数量
            var carts = mutableListOf<CartItem0>()
            //
            cartAdapter.data.forEach {
                if (it.isChecked){
                    count ++
                }
            }
            //判断数量
            if (count > 0){
                var ids = arrayOf<Int>()
                //
                cartAdapter.data.forEach {
                    if (it.isChecked){
                        ids += it.id
                        carts.add(it)
                    }
                }
                //调用
                viewModel.cartDelete(ids)
                //刷新页面数据
                cartAdapter.data.removeAll(carts)
                cartAdapter.notifyDataSetChanged()
                 checkAmount()
            } else {
                ToastUtils.showLong("请选择商品")
            }
        }

        //点击提交订单，进行预下单，提交成功跳转到预下单页面
        binding.tvOrder.setOnClickListener {
            val size = cartAdapter.data.filter { it.isChecked }.size
            //
            if (size > 0){
                //创建集合保存购物车商品的id
                val list = mutableListOf<OrderDetail>()
                //
                cartAdapter.data.filter { it.isChecked }
                    .forEach {
                        val orderDetail = OrderDetail()
                        //获取购物车商品的id
                        orderDetail.shoppingCartId = it.id
                        //
                        list.add(orderDetail)
                    }
                //
                val pPreOrder = PPreOrder()
                pPreOrder.preOrderType = "shoppingCart"
                pPreOrder.orderDetails = list//具体添加购物车的id
                //调用预订单
                viewModel.preOrder(pPreOrder)

            } else {
                ToastUtils.showLong("请选择商品至少一个")
            }
        }
    }

    //价钱
    private fun checkAmount() {
        var total = 0f
        var count = 0
        //
        cartAdapter.data.forEach {
            if (it.isChecked){
                total += it.price.toFloat() * it.cartNum
                count++
            }
        }
        //
        binding.tvMoney.text = "$$total"
        binding.tvCount.text = "购物车${cartAdapter.data.size}"
        //判断全选
        if (count == cartAdapter.data.size && count > 0){
            binding.cb.isChecked = true
            binding.cb.text = "全选${count}"
        } else {
            binding.cb.isChecked = false
            binding.cb.text = "全选${count}"
        }
    }

    override fun initDate() {

        //
        viewModel.cartSuccess.observe(this){
            if (it.code == 200){
                cartAdapter.data.clear()
                cartAdapter.data.addAll(it.data.list)
                cartAdapter.notifyDataSetChanged()
                //
                binding.tvCount.text = "购物车：${it.data.total}"
            }
            //
            ToastUtils.showLong(it.message)
        }

        //
        viewModel.cartUpdateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        //
        viewModel.cartUpdateFail.observe(this){
            ToastUtils.showLong(it)
        }

        //
        viewModel.preOrderSuccess.observe(this){
            if (it.code == 200){
                ARouter.getInstance().build("/app/CreateOrderActivity")
                    .withString("preOrderNo",it.data.preOrderNo).navigation()
            }
            //
            ToastUtils.showLong(it.message)
        }
    }
}